<?php

class BookController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			// 'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','type'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','message','vote'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        $model=$this->loadModel($id);
        $model->browsertimes=$model->browsertimes+1;
        $model->save();
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Book;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Book']))
		{
			$model->attributes=$_POST['Book'];
            $model->browsertimes=0;
            $model->vote=0;
            $timeString=time();
            $image=CUploadedFile::getInstance($model, 'picture');

            if( is_object($image) && get_class($image) === 'CUploadedFile' ){
                $model->picture=$timeString .'-'. Yii::app()->User->name . '.' . $image->getExtensionName();
            }
            else
            {
                $model->picture= 'default.jpg';
            }
			if($model->save())
                if(is_object($image) && get_class($image) === 'CUploadedFile'){
                    $image->saveAs('images/' . $model->picture);
                }
                // if(!empty($model->file))
                // {
                    // $model->file = CUploadedFile::getInstance($model, 'file');
                    // $model->file->saveAs('docs/' . $model->file->name);
                // }
                // $imageResize = Yii::app()->image->load('images/' . $model->picture->name);
                // $imageResize->resize(400, 100)->rotate(-45)->quality(75)->sharpen(20);
                // $imageResize->save('images/' . $model->picture->name); // or $image->save('images/small.jpg');
				$this->redirect(array('view','id'=>$model->id));
            }

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Book']))
		{
			$model->attributes=$_POST['Book'];
            $image=CUploadedFile::getInstance($model, 'picture');
            $timeString=time();

            if( is_object($image) && get_class($image) === 'CUploadedFile' ){
                $model->picture=$timeString .'-'. Yii::app()->User->name . '.' . $image->getExtensionName();
            }
            else if(!$model->picture)
            {
                $model->picture= 'default.jpg';
            }
			if($model->save())
                if(is_object($image) && get_class($image) === 'CUploadedFile'){
                    $image->saveAs('images/' . $model->picture);
                }
                // $model->picture->saveAs('docs/' . $model->file->name);
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionMessage()
	{
        if(Yii::app()->request->isAjaxRequest){//是否ajax请求
            $model = new Message();
            $model->bookid=(int)Yii::app()->request->getParam('id');//getparam 会获得 get post 变量 ，原来也可以接收json处理后的变量
            $model->time = date('Y-m-d H:i:s');
            $model->content = Yii::app()->request->getParam('message');
            $model->userid = Yii::app()->User->id;
            if($model->save()){
                // echo CJSON::encode(array('val'=>$model->remark));//Yii 的方法将数组处理成json数据
                echo true;
            }
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Book');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionType($typeid)
	{
        $dataProvider=new CActiveDataProvider('Book', array(
            'criteria'=>array(
                'condition'=>'typeid='.$typeid,
            ),
        ));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * 投票
	 */
	public function actionVote()
	{
        if(Yii::app()->request->isAjaxRequest) //是否ajax请求
        {
            $id=(int)Yii::app()->request->getParam('id');//getparam 会获得 get post 变量 ，原来也可以接收json处理后的变量
            $model=$this->loadModel($id);
            $model->vote=$model->vote+1;
            $voteNum=$model->vote;
            $model->save();
            echo $voteNum;
        }
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Book('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Book']))
			$model->attributes=$_GET['Book'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Book the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Book::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Book $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='book-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
